<template>
  <div class="common-layout">
    <el-container>
     
      <el-main style="height: 1000px; ">
        <el-card style="width: 1200px;height: 450px;margin-bottom: 15px;" shadow="always" >
          <span style="width: 2px;">基础信息</span>
           <el-divider />
            <div>
              <el-form
                ref="ruleFormRef"
                style="max-width: 600px"
                :model="ruleForm"
                :rules="rules"
                label-width="auto"
              >
              <el-row style="width: 1000px;">
                <el-col :span="12" >
                  <el-form-item label="单号" prop="inventoryNnumber">
                    <el-input v-model="ruleForm.inventoryNnumber" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="盘点类型" prop="inventoryType">
                  <el-select v-model="ruleForm.inventoryType" placeholder="盘点类型">
                    <el-option label="全部盘点" :value="1" />
                    <el-option label="部分盘点" :value="2" />
                  </el-select>
                </el-form-item>
                </el-col>
              </el-row>
              <el-row style="width: 1000px;">
                <el-col :span="12">
                  <el-form-item label="开始时间" required prop="inventoryStartTime">
                      <el-date-picker
                        v-model="ruleForm.inventoryStartTime"
                        type="date"
                        aria-label="Pick a date"
                        placeholder="开始时间"
                        style="width: 100%"
                      />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束时间" required prop="inventoryEndTime">
                      <el-date-picker
                        v-model="ruleForm.inventoryEndTime"
                        type="date"
                        aria-label="Pick a date"
                        placeholder="结束时间"
                        style="width: 100%"
                      />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row style="width: 1000px;">
                <el-col :span="12">
                  <el-form-item label="盘点范围" prop="inventoryRange">
                  <el-select v-model="ruleForm.inventoryRange" placeholder="盘点范围">
                    <el-option label="仓库区域" :value="1" />
                    <el-option label="商品类别" :value="2" />
                  </el-select>
                </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="仓库名称" prop="storeId">
                  <el-select v-model="ruleForm.storeId" placeholder="仓库名称">
                    <el-option v-for="a in storedata" :label="a.storeName" :value="a.id" />
                  </el-select>
                </el-form-item>
                </el-col>
              </el-row>

              <el-row style="width: 1000px;">
                <el-col :span="12">
                  <el-form-item :inline="true" label="经办人" prop="attnName">
                     <el-col :span="10">
                      <el-input v-model="ruleForm.attnName"/>
                     </el-col>
                      <el-col :span="2" style="margin-left: 10px;">
                       <el-button @click="openJing()">选择</el-button>
                     </el-col>
                  </el-form-item>
                </el-col>
                <el-col :span="12">

                </el-col>
              </el-row>
              <el-row style="width: 1000px;">
                <el-col :span="24">
                  <el-form-item label="备注" prop="note">
                      <el-input v-model="ruleForm.note" type="textarea" />
                  </el-form-item>
                </el-col>
              </el-row>
                <el-form-item style="right: auto;">
                  <el-button v-if="ruleForm.id==0" type="primary" @click="submitForm(ruleFormRef)">
                    保存
                  </el-button>
                  <el-button v-if="ruleForm.id!=0" type="primary" @click="">
                    编辑
                  </el-button>
                  <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
              </el-form>
            </div>


        </el-card>
        <el-card style="width: 1200px;height: 500px;" shadow="always" >
          <span style="width: 2px;">盘点明细</span>
            <el-divider />
              <div style="margin-bottom: 15px;">
                <el-button type="success" plain @click="opensGoods()">新增</el-button>
              </div>
        </el-card>
      </el-main>
    </el-container>
  </div>


<!-- 经办人 -->
  <el-dialog v-model="dialogTableVisible" title="经办人" width="800" draggable align-center>
    <el-table :data="tableData">
       <el-table-column fixed type="index" label="序号" width="60px" />
            <el-table-column prop="userName" label="用户"  />
            <el-table-column prop="roleName" label="角色" width="200px"/>
            <el-table-column prop="sex" label="性别" >
                <template v-slot="scoped">
                    <el-tag type="primary" v-if="scoped.row.sex==false">男</el-tag>
                    <el-tag type="danger" v-if="scoped.row.sex==true">女</el-tag>
                </template>
            </el-table-column>
            <el-table-column fixed="right" prop="address" label="操作" width="160">
                <template v-slot="scoped">
                    <el-button type="warning" @click="dispose(scoped.row)" round>选择</el-button>
                </template>
            </el-table-column>
    </el-table>
    <div class="demo-pagination-block" style="margin-top: 20px;">
            <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[15, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.listcount"
            />
    </div>
  </el-dialog>

<!-- 货品列表 -->
<el-dialog v-model="logic.goodsopen" title="货品列表" width="800"  draggable align-center>
  <el-form :inline="true" :model="can" class="demo-form-inline" style="margin-top: 12px;">
            <el-form-item label="">
              <el-input v-model="can.SearchKeyword" placeholder="货品名称、编号、规格"/>
            </el-form-item>
            <el-form-item>
            <el-button type="primary" @click="getgoodsData()">查询</el-button>
            <el-button type="primary" @click="addinventoryGoods()">保存</el-button>
            </el-form-item>
        </el-form>
      <el-table
    ref="multipleTableRef"
    :data="goodsData"
    row-key="id"
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column property="goodsNumber" label="货品单号"  />
    <el-table-column property="goodsName" label="货品名称" />
    <el-table-column property="goodsModel" label="货品规格" />
    <el-table-column property="goodsUnit" label="货品单位" />
    <el-table-column property="systemNum" label="系统库存" />
    <el-table-column property="actualNum" label="实际库存" />
  </el-table>
  <div class="demo-pagination-block" style="margin-top: 20px;">
            <el-pagination
            v-model:current-page="pages.PageIndex"
            v-model:page-size="pages.PageSize"
            :page-sizes="[15, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pages.listcount"
            />
    </div>
</el-dialog>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import {useCounterStore} from '@/stores/counter'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { inventoryRead, inventoryWrite, readBasic } from '@/Helper/axiosSetting';
import { useRoute, useRouter } from 'vue-router';
import type { TableInstance } from 'element-plus'
const router=useRouter();
const route=useRoute();
const use=useCounterStore();
onMounted(()=>{
    getstoredata()
    creatNumber()
    getRuleform()
})

// 监听页面可见性变化，自动刷新数据
watch(() => document.visibilityState, (newState, oldState) => {
  if (newState === 'visible' && oldState === 'hidden') {
    console.log('🔄 页面重新可见，刷新盘点配置数据')
    getstoredata()
    getRuleform()
  }
})


const creatNumber=()=>{
  // 生成8位随机数
  const randomNumber = Math.floor(Math.random() * 100000000).toString().padStart(8, '0');
  // 生成PDDH开头的编号
  const inventoryNumber = 'PDDH' + randomNumber;
  // 赋值给表单
  ruleForm.inventoryNnumber = inventoryNumber;
}

const ruleFormRef = ref<FormInstance>()
//表单实体
const ruleForm = reactive({
  "id":0,
   "inventoryNnumber": "",
  "inventoryStatus": 3,
  "mid": 1,
  "inventoryType": '',
  "storeId": [Number] ,
  "inventoryRange": '',
  "inventoryStartTime": "",
  "inventoryEndTime": "",
  "note": "",
  "taskType": 1,
    "attnId": 0,
  "attnName": "",
   "createUserId": use.UserInfo.Uid,
  "createUserName":use.UserInfo.UserName 
})
//表单验证
const rules = reactive<FormRules>({
  inventoryNnumber: [
    { required: true, message: '库存盘点单号必填', trigger: 'blur' },
  ],
  inventoryType: [
    {
      required: true,
      message: '盘点类型不能为空',
      trigger: 'change',
    },
  ],
  storeId: [
    {
      required: true,
      message: '仓库必选',
      trigger: 'change',
    },
  ],
  inventoryStartTime: [
    {
      type: 'date',
      required: true,
      message: '盘点开始时间',
      trigger: 'change',
    },
  ],
  inventoryEndTime: [
    {
      type: 'date',
      required: true,
      message: '盘点结束时间',
      trigger: 'change',
    },
  ],
  inventoryRange: [
    {
      required: true,
      message: '盘点范围',
      trigger: 'change',
    },
  ],
})
//提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      inventoryWrite.post("/api/InventoryWrite/AddInventoryTask",ruleForm).then(res=>{
        if(res.data.code==200){
          ElMessage.success(res.data.message)
          router.push({
            path:'/InventoryTask'
          })
        }else{
          ElMessage.error("添加失败")
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))


//获取用户列表
const tableData= ref([])
const page=reactive({
    PageIndex:1,
    PageSize:5,
    listcount:0
})
watch(page,()=>{
    getUserList()
},{deep:true})
const getUserList=()=>{
    readBasic.get("api/Manage/GetUserList",{params:{
        PageIndex:page.PageIndex,
        PageSize:page.PageSize
    }}).then(res=>{
        tableData.value=res.data.data.list
        page.listcount=res.data.data.recordCount
    })
}

const dialogTableVisible = ref(false)

const openJing=()=>{
  dialogTableVisible.value=true
  getUserList()
}
//确定经办人
const dispose=(row:any)=>{
  ruleForm.attnId=row.id,
  ruleForm.attnName=row.userName
  dialogTableVisible.value=false
}
const storedata=ref<any>([])
const getstoredata=()=>{
  inventoryRead.get("/api/InventoryRead/GetStoreList").then(res=>{
    storedata.value=res.data.data.list
  })
}



//数据反填
const getRuleform=()=>{
  inventoryRead.get("/api/InventoryRead/GetInventoryTaskById",{params:{id:route.query.id}}).then(res=>{
    ruleForm.storeId=res.data.data.storeId
    Object.assign(ruleForm,res.data.data)
  })
}


//货品列表

const logic=reactive({
goodsopen:false
})

const opensGoods=()=>{
  logic.goodsopen=true
  getgoodsData()
}

const can=reactive({
  SearchKeyword:''
})

const pages=reactive({
  PageIndex:1,
  PageSize:5,
  listcount:0
})
watch(pages,()=>{
getgoodsData()
},{deep:true})

const goodsData=ref([])
const getgoodsData=()=>{
  inventoryRead.get("/api/InventoryRead/GetGoodsList",{params:{
    SearchKeyword:can.SearchKeyword,
    PageIndex:pages.PageIndex,
    PageSize:pages.PageSize
  }}).then(res=>{
    goodsData.value=res.data.data.list
    pages.listcount=res.data.data.count
  })
}



const multipleTableRef = ref<TableInstance>()

const multipleSelection = ref<any>([])


//获取批量先择的货品
const ids=ref<any>([])
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
  ids.value = multipleSelection.value.map((item: any) => item.id)
  console.log('选中的数据:', multipleSelection.value)
  console.log('提取的ID列表:', ids.value.toString())
}

//为盘点单，添加盘点货品
const addinventoryGoods=()=>{
  
  inventoryWrite.post("/api/InventoryWrite/AddInventoryGoods",{id:route.query.id,ids:ids.value.toString()}).then(res=>{
    if(res.data.code==200){
      ElMessage.success('添加成功')
      router.push({
        path:'/InventoryTask'
      })

    }else{
      ElMessage.error('添加失败')
    }
  })
}


</script>